package cn.edu.zut.qixiang.repository;

import cn.edu.zut.qixiang.entity.WeatherData;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author 86178
 */

@Repository
public interface WeatherDataRepository extends JpaRepository<WeatherData, Long> {

    /**
     * 根据区域获取最近N条数据
     */
    @Query("SELECT w FROM WeatherData w WHERE w.district = :district ORDER BY w.timestamp DESC")
    List<WeatherData> findRecentByDistrict(@Param("district") String district, Pageable pageable);

    /**
     * 获取指定时间之后的数据
     */
    @Query("SELECT w FROM WeatherData w WHERE w.timestamp > :timestamp ORDER BY w.timestamp ASC")
    List<WeatherData> findByTimestampAfter(@Param("timestamp") LocalDateTime timestamp);

    /**
     * 获取所有区域的最新数据
     */
    @Query("SELECT w FROM WeatherData w WHERE w.timestamp IN (" +
            "SELECT MAX(w2.timestamp) FROM WeatherData w2 GROUP BY w2.district" +
            ")")
    List<WeatherData> findLatestAllDistricts();

    /**
     * 统计区域数据量
     */
    @Query("SELECT COUNT(w) FROM WeatherData w WHERE w.district = :district")
    Long countByDistrict(@Param("district") String district);

}